package me.zachwhaley.android.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

public class SelectionBuilder
{
	private static final String TAG = "SelectionBuilder";
	private static final boolean LOGV = false;

	private String table = null;
	private Map<String, String> projectionMap = new HashMap<String, String>();
	private StringBuilder selection = new StringBuilder();
	private ArrayList<String> selectionArgs = new ArrayList<String>();

	/**
	 * Reset any internal state, allowing this builder to be recycled.
	 * @return This SelectionBuilder
	 */
	public SelectionBuilder reset()
	{
		table = null;
		selection.setLength(0);
		selectionArgs.clear();
		return this;
	}

	/**
	 * Append the given selection clause to the internal state. Each clause is
     * surrounded with parenthesis and combined using {@code AND}.
	 * @param selection
	 * @param selectionArgs
	 * @return This SelectionBuilder
	 */
	public SelectionBuilder where(String selection, String... selectionArgs)
	{
		if (TextUtils.isEmpty(selection))
		{
			if (selectionArgs != null && selectionArgs.length > 0)
			{
				throw new IllegalArgumentException("Valid selection required when including arguments=");
			}
			return this;
		}

		if (this.selection.length() > 0)
		{
			this.selection.append(" AND ");
		}

		this.selection.append("(").append(selection).append(")");
		if (selectionArgs != null)
		{
			for (String arg : selectionArgs)
			{
				this.selectionArgs.add(arg);
			}
		}

		return this;
	}

	/**
	 * 
	 * @param table
	 * @return This SelectionBuilder
	 */
	public SelectionBuilder table(String table)
	{
		this.table = table;
		return this;
	}

	/**
	 * 
	 */
	private void assertTable()
	{
		if (this.table == null)
		{
			throw new IllegalStateException("Table not specified");
		}
	}

	/**
	 * 
	 * @param column
	 * @param table
	 * @return This SelectionBuilder
	 */
	public SelectionBuilder mapToTable(String column, String table)
	{
		projectionMap.put(column, table + "." + column);
		return this;
	}

	/**
	 * 
	 * @param fromColumn
	 * @param toClause
	 * @return This SelectionBuilder
	 */
	public SelectionBuilder map(String fromColumn, String toClause)
	{
		projectionMap.put(fromColumn, toClause + " AS " + fromColumn);
		return this;
	}

	/**
	 * Return selection string for current internal state.
	 * @return Current selection string
	 */
	public String getSelection()
	{
		return selection.toString();
	}

	/**
	 * Return selection arguments for current internal state.
	 * @return Current selection arguments 
	 */
	public String[] getSelectionArgs()
	{
		return selectionArgs.toArray(new String[selectionArgs.size()]);
	}

	/**
	 * 
	 * @param columns
	 */
	private void mapColumns(String[] columns)
	{
		for (int n = 0; n < columns.length; ++n)
		{
			final String target = projectionMap.get(columns[n]);
			if (target != null)
			{
				columns[n] = target;
			}
		}
	}

	/**
	 * Execute query using the current internal state as {@code WHERE} clause.
	 * @param db
	 * @param columns
	 * @param orderBy
	 * @return Result from query
	 */
	public Cursor query(SQLiteDatabase db, String[] columns, String orderBy)
	{
		return query(db, columns, null, null, orderBy, null);
	}

	/**
	 * Execute query using the current internal state as {@code WHERE} clause.
	 * @param db
	 * @param columns
	 * @param groupBy
	 * @param having
	 * @param orderBy
	 * @param limit
	 * @return Result from query
	 */
	public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
			String having, String orderBy, String limit)
	{
		assertTable();
		if (columns != null)
		{
			mapColumns(columns);
		}
		if (LOGV)
		{
			Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") "
					+ this);
		}
		return db.query(table, columns, getSelection(), getSelectionArgs(),
				groupBy, having, orderBy, limit);
	}

	/**
	 * Execute update using the current internal state as {@code WHERE} clause.
	 * @param db
	 * @param values
	 * @return Number of rows updated
	 */
	public int update(SQLiteDatabase db, ContentValues values)
	{
		assertTable();
		if (LOGV)
		{
			Log.v(TAG, "update() " + this);
		}
		return db.update(table, values, getSelection(), getSelectionArgs());
	}

	/**
	 * Execute delete using the current internal state as {@code WHERE} clause.
	 * @param db
	 * @return Number of rows deleted
	 */
	public int delete(SQLiteDatabase db)
	{
		assertTable();
		if (LOGV)
		{
			Log.v(TAG, "delete() " + this);
		}
		return db.delete(table, getSelection(), getSelectionArgs());
	}

	@Override
	public String toString()
	{
		return "SelectionBuilder[table=" + table + ", selection="
				+ getSelection() + ", selectionArgs="
				+ Arrays.toString(getSelectionArgs()) + "]";
	}
}
